package cn.edu.swu.auth;

import cn.edu.swu.book.Book;
import cn.edu.swu.book.DatabaseUtils;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet(name = "ShoppingServlet", urlPatterns = {"/shopping"})
public class ShoppingServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 重定向到Shopping.html页面
        response.sendRedirect("shopping.html");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求参数编码，防止中文乱码
        request.setCharacterEncoding("UTF-8");

        // 获取书籍ID参数
        String bookIdParam = request.getParameter("bookId");
        int bookId;
        try {
            bookId = Integer.parseInt(bookIdParam); // 将字符串参数转换为整数
        } catch (NumberFormatException e) {
            // 如果参数不是有效的整数，设置状态码或发送错误信息
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("Invalid book ID.");
            return;
        }

        // 使用DatabaseUtils获取书籍详细信息
        Book book = null;
        try {
            book = DatabaseUtils.getBookDetailsFromId(bookId);
            if (book == null) {
                // 如果书籍不存在，设置状态码或发送错误信息
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write("Book not found.");
            } else {
                // 添加书籍到购物车
                boolean added = addToCart(book);
                if (added) {
                    // 如果添加成功，重定向到购物车页面
                    response.sendRedirect("shopping.html");
                } else {
                    // 如果添加失败，设置状态码或发送错误信息
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.getWriter().write("Error adding book to cart.");
                }
            }
        } catch (SQLException e) {
            // 数据库异常处理
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("Database error: " + e.getMessage());
        }
    }

    // 将书籍添加到购物车的方法
    private boolean addToCart(Book book) {
        String sql = "INSERT INTO shopping (id, name, author, price, memo, publish, image) VALUES (?, ?, ?, ?, ?, ?, ?)";
        try (Connection connection = DatabaseUtils.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {

            statement.setInt(1, book.getId());
            statement.setString(2, book.getName());
            statement.setString(3, book.getAuthor());
            statement.setDouble(4, book.getPrice());
            statement.setString(5, book.getMemo());
            statement.setDate(6, new java.sql.Date(book.getPublish().getTime()));
            statement.setString(7, book.getImage());

            int rowsAffected = statement.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
}